//
//  RTCManager.m
//  GLUZ
//
//  Created by GS on 2025/2/11.
//

#import "RTCManager.h"
#import "YYModel.h"
#import "MTManager.h"

@interface RTCManager()<ZegoAudioDataHandler, RealtimeTranslationHandler>

@property (nonatomic, strong) RTManager *rtManager;

@end
@implementation RTCManager

+ (RTCManager *)shared{
    static RTCManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });
    return shared;
}


#pragma mark  科大讯飞实时传译
/// 初始化实时传译
/// - Parameters:
///   - lang: 原语种
///   - targetLang: 要翻译成的语种
- (void)startRealtimeTranslationLang:(NSString *)lang targetLang:(NSString *)targetLang {
    // 已接入ZegoRealtimeTranslation 没有使用，RTManager 使用的是webscoket连接的科大讯飞的webapi
    [self stopRealtimeTranslation];
    self.rtManager = [[RTManager alloc] init];
    self.rtManager.lang = lang;
    self.rtManager.targetLang = targetLang;
    self.rtManager.eventHandler = self;
    // Thread running at User-initiated quality-of-service class waiting on a lower QoS thread running at Default quality-of-service class. Investigate ways to avoid priority inversions
    // 以用户发起的服务质量类运行的线程正在等待以默认服务质量类运行的较低QoS的线程。研究避免优先级反转的方法
    // 之前使用的defalt，会出现上面的提示，DISPATCH_QUEUE_PRIORITY_DEFAULT 前面正运行着一个低的 QoS 线程，可能造成优先级反转，换成 DISPATCH_QUEUE_PRIORITY_LOW 就不会出现警告了
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // 需要放到线程中，否则链接不上
        [self.rtManager connectWebSocket];
    });
}

- (void)startRealtimeTranslationLang {
    NSInteger type = [[NSUserDefaults standardUserDefaults] integerForKey:@"country"];
    NSLog(@"当前国家类型 %ld", (long)type);
    // 中国 zh 不好使，要使用 cn
    NSString * userLanguage = type == 0? @"cn" : @"ru";
    
    NSString * targetLang = type == 0? @"ru" : @"cn";
    
    [self startRealtimeTranslationLang:userLanguage targetLang:targetLang];
}


- (void)stopRealtimeTranslation {
    [self.rtManager disconnectWebSocket];
    self.rtManager = nil;
}

#pragma mark RealtimeTranslationHandler
/// 翻译内容
- (void)onRecognizedText:(NSString * _Nullable)sttText translatedText:(NSString * _Nullable)translatedText{
    // NSLog(@"机翻 原语言：%@，目标语言：%@", self.rtManager.lang, self.rtManager.targetLang);
    [MTManager translationFrom:self.rtManager.lang to:self.rtManager.targetLang text:sttText success:^(NSString *src, NSString * _Nonnull dst) {
        //        NSLog(@"翻译原文 %@", sttText);
        //        NSLog(@"翻译结果 %@", dst);
        //        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
            IMRecognizeModel *model = [IMRecognizeModel new];
            model.type = @"1";
            model.text = [NSString stringWithFormat:@"%@: %@(%@)", username, sttText, dst];
            if (self.realtimeTranslationMessage) {
                self.realtimeTranslationMessage(model);
                // 翻译内容通过房间的SEI 消息获取
                [self sendSEIMessage:model.yy_modelToJSONString];
            }
        });
    } failure:^(NSError *error) {
        
    }];
    //    if (self.realtimeTranslationMessage) {
    //        IMRecognizeModel *model = [IMRecognizeModel new];
    //        NSInteger type = [[NSUserDefaults standardUserDefaults] integerForKey:@"country"];
    //        if (type == 0) {
    //            model.username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
    //        } else {
    //            model.username = [[NSUserDefaults standardUserDefaults] stringForKey:@"usernameRu"];
    //        }
    //        model.type = @"1";
    //        model.text = sttText;
    //        model.trans = translatedText;
    //        self.realtimeTranslationMessage(model);
    //        // 翻译内容通过房间的SEI 消息获取
    //        [self sendSEIMessage:model.yy_modelToJSONString];
    //    }
}

/// 翻译关闭
- (void)didCloseWithCode:(NSInteger)code reason:(NSString *)reason{
    
}

/// 翻译错误回调
- (void)onError:(NSError *)error{
    
}



#pragma mark  音频采集控制用于翻译

// 开始音频采集
- (void)startAudioDataObserver {
    // 需要的音频数据类型 Bitmask，此处示例四个回调都开启
    ZegoAudioDataCallbackBitMask bitmask = ZegoAudioDataCallbackBitMaskCaptured |  ZegoAudioDataCallbackBitMaskPlayer;
    
    // 需要的音频数据参数，此处示例单声道、16 K
    ZegoAudioFrameParam *param = [[ZegoAudioFrameParam alloc] init];
    param.channel = ZegoAudioChannelMono;
    param.sampleRate = ZegoAudioSampleRate16K;
    
    // 开启获取原始音频数据功能
    [[ZegoExpressEngine sharedEngine] startAudioDataObserver:bitmask param:param];
    
    // 设置音频数据回调
    [[ZegoExpressEngine sharedEngine] setAudioDataHandler:self];
}

// 停止音频采集
- (void)stopAudioDataObserver{
    [[ZegoExpressEngine sharedEngine] stopAudioDataObserver];
}

// 根据需要实现以下四个回调，分别对应上述 Bitmask 的四个选项
- (void)onCapturedAudioData:(const unsigned char *)data dataLength:(unsigned int)dataLength param:(ZegoAudioFrameParam *)param {
    // 本地采集音频数据，推流后可收到回调
    NSData *sendData = [NSData dataWithBytes:data length:dataLength];
    // 实时传译
    [self.rtManager sendAudioData:sendData];
}


#pragma mark 房间翻译消息
// 发送SEI 消息
- (void)sendSEIMessage:(NSString *)message {
    [[ZegoExpressEngine sharedEngine] sendSEI:[message dataUsingEncoding:NSUTF8StringEncoding]];
}

// 收到其他SEI 消息
- (void)onPlayerSyncRecvSEI:(NSData *)data streamID:(NSString *)streamID{
    NSString *jsongStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self translationMessageWith:jsongStr];
}

// 处理翻译消息
- (void)translationMessageWith:(NSString *)jsongStr{
    if (self.realtimeTranslationMessage) {
        IMRecognizeModel *model = [IMRecognizeModel yy_modelWithJSON:jsongStr];
        self.realtimeTranslationMessage(model);
    }
}

@end
